package com.example.hotel_lxy.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.example.hotel_lxy.R;
import com.example.hotel_lxy.application.ARouterPath;
import com.example.hotel_lxy.bean.BeanBean;
import com.example.hotel_lxy.bean.EventBusBean;
import com.example.hotel_lxy.bean.EventBusResereBean;
import com.example.hotel_lxy.bean.IncrementGetIncreaseBean;
import com.example.hotel_lxy.bean.IncrementIncreaseSaveBean;
import com.example.hotel_lxy.bean.IncrementServiceBean;
import com.example.hotel_lxy.net.Api;
import com.example.hotel_lxy.utils.SPUtils;
import com.google.gson.Gson;
import com.ysxsoft.common_base.base.BaseActivity;
import com.ysxsoft.common_base.base.RBaseAdapter;
import com.ysxsoft.common_base.base.RViewHolder;
import com.ysxsoft.common_base.utils.JsonUtils;
import com.ysxsoft.common_base.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 增值服务
 */
@Route(path = "/main/IncrementServiceActivity")
public class IncrementServiceActivity extends BaseActivity {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.rv_increment)
    RecyclerView rvIncrement;
    @BindView(R.id.text_qd)
    TextView textQd;
    private List<ServiceBean> mlist = new ArrayList<>();
    private List<ServiceBean> mlistq = new ArrayList<>();
    private List<ServiceBean> getmlist = new ArrayList<>();
    private float total;
    private  String anIntid;
    @Autowired
    String id;
    public static void start(String id) {
        ARouter.getInstance().build(ARouterPath.getIncrementServiceActivity())
                .withString("id",id)
                .navigation();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_increment_service;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void doWork() {
        super.doWork();
        ARouter.getInstance().inject(this);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        anIntid=id;
        if(!id.equals("")&&id!=null){
            showDataGetService();
        }else{
            showDateService();
        }

        textQd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < rvIncrement.getChildCount(); i++) {
                    View childAt = rvIncrement.getChildAt(i);
                    EditText edit_morey= childAt.findViewById(R.id.edit_morey);
                    int finalI = i;
                    mlist.get(finalI).setMorey(edit_morey.getText().toString());
                }

                if(!id.equals("")&&id!=null){
                    for (int i = 0; i <mlist.size() ; i++) {
                        if(!mlist.get(i).getMorey().equals("")){
                                ServiceBean serviceBean = new ServiceBean();
                                serviceBean.setId(mlist.get(i).getId() + "");
                                serviceBean.setName(mlist.get(i).getName());
                                serviceBean.setMorey(mlist.get(i).getMorey());
                                serviceBean.setNumber(mlist.get(i).getNumber());
                                mlistq.add(serviceBean);
                        }else{
                            if(Integer.valueOf(mlist.get(i).getNumber())>0){
                                ToastUtils.shortToast(IncrementServiceActivity.this,"请填写"+mlist.get(i).getName()+"金额");
                                mlistq.clear();
                                return;
                            }
                        }
                    }
                    showAnd();
                }else{
                    for (int i = 0; i <mlist.size() ; i++) {
                        if(Integer.valueOf(mlist.get(i).getNumber())>0){
                            if(mlist.get(i).getMorey().equals("")){
                                ToastUtils.shortToast(IncrementServiceActivity.this,"请填写"+mlist.get(i).getName()+"金额");
                                mlistq.clear();
                                return;
                            }
                            ServiceBean serviceBean = new ServiceBean();
                            serviceBean.setId(mlist.get(i).getId() + "");
                            serviceBean.setName(mlist.get(i).getName());
                            serviceBean.setMorey(mlist.get(i).getMorey());
                            serviceBean.setNumber(mlist.get(i).getNumber());
                            mlistq.add(serviceBean);
                        }
                    }
                    showAnds();
                }
            }
        });
    }

    private void showAnds() {
        Gson gson = new Gson();
        String s = gson.toJson(mlistq);
        String token = SPUtils.get(IncrementServiceActivity.this, "token", "").toString();
        OkHttpUtils.post()
                .url(Api.POST_SCHEDULED_INCREASE_SAVE)
                .addHeader("flag", token)
                .addParams("increase", s)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "增值服务保存与修改onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "增值服务保存与修改onResponse   " + response);
                        if(response.equals("")){
                            EventBusResereBean eventBusBean=new EventBusResereBean();
                            eventBusBean.setType(4);
                            eventBusBean.setId("");
                            eventBusBean.setMoney("");
                            EventBus.getDefault().post(eventBusBean); //普通事件发布
                            finish();
                            return;
                        }
                        BeanBean beanBean= JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("4")){
                            SPUtils.put(mContext,"token","");
                            Intent intent = new Intent(mContext, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        IncrementIncreaseSaveBean incrementIncreaseSaveBean = JsonUtils.parseByGson(response, IncrementIncreaseSaveBean.class);
                        if (beanBean.getCode().equals("0")) {
                            SPUtils.put(IncrementServiceActivity.this, "cid", incrementIncreaseSaveBean.getData().getCid());
                            for (int i = 0; i <mlist.size() ; i++) {
                                if(!mlist.get(i).getMorey().equals("")&&mlist.get(i).getNumber()!=0){
                                    float v = convertToFloat(mlist.get(i).getMorey(), 0);
                                    int number = mlist.get(i).getNumber();
                                    float s= v*number;
                                    total= total+s;
                                }
                            }
                            EventBusResereBean eventBusBean=new EventBusResereBean();
                            eventBusBean.setType(4);
                            eventBusBean.setId(incrementIncreaseSaveBean.getData().getCid()+"");
                            eventBusBean.setMoney(total+"");
                            EventBus.getDefault().post(eventBusBean); //普通事件发布
                            finish();
                        }
                    }
                });
    }

    private void showDataGetService() {
        OkHttpUtils.post()
                .url(Api.POST_SCHEDULED_GET_INCREASE)
                .addHeader("flag", SPUtils.get(IncrementServiceActivity.this, "token", "").toString())
                .addParams("id", id)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "获取已保存的增值服务onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "获取已保存的增值服务onResponse   " + response);
                        BeanBean beanBean= JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("4")){
                            SPUtils.put(mContext,"token","");
                            Intent intent = new Intent(mContext, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        IncrementGetIncreaseBean incrementGetIncreaseBean = JsonUtils.parseByGson(response, IncrementGetIncreaseBean.class);
                        if(beanBean.getCode().equals("0")){
                            for (int i = 0; i < incrementGetIncreaseBean.getData().getList().size(); i++) {
                                IncrementGetIncreaseBean.DataBean.ListBean listBean = incrementGetIncreaseBean.getData().getList().get(i);
                                ServiceBean serviceBean = new ServiceBean();
                                serviceBean.setId(listBean.getOid() + "");
                                serviceBean.setName("");
                                if(listBean.getMoney().equals("0.00")){
                                    serviceBean.setMorey("");
                                }else{
                                    serviceBean.setMorey(listBean.getMoney());
                                }
                                serviceBean.setNumber(listBean.getNum());
                                getmlist.add(serviceBean);
                            }
                            showDateService();
                        }

                    }
                });
    }

    private void showAnd() {
        String s;
        if(mlistq.size()!=0){
            Gson gson = new Gson();
            s = gson.toJson(mlistq);
        }else{
            s ="[]";
        }
        String token = SPUtils.get(IncrementServiceActivity.this, "token", "").toString();
        OkHttpUtils.post()
                .url(Api.POST_SCHEDULED_INCREASE_SAVE)
                .addHeader("flag", token)
                .addParams("increase", s)
                .addParams("id",id)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "增值服务保存与修改onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "增值服务保存与修改onResponse   " + response);
                        if(response.equals("")){
                            EventBusResereBean eventBusBean=new EventBusResereBean();
                            eventBusBean.setType(4);
                            eventBusBean.setId("");
                            eventBusBean.setMoney("");
                            EventBus.getDefault().post(eventBusBean); //普通事件发布
                            finish();
                            return;
                        }
                        BeanBean beanBean= JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("4")){
                            SPUtils.put(mContext,"token","");
                            Intent intent = new Intent(mContext, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        IncrementIncreaseSaveBean incrementIncreaseSaveBean = JsonUtils.parseByGson(response, IncrementIncreaseSaveBean.class);
                        if (beanBean.getCode().equals("0")) {
                            SPUtils.put(IncrementServiceActivity.this, "cid", incrementIncreaseSaveBean.getData().getCid());
                            for (int i = 0; i <mlist.size() ; i++) {
                                if(mlist.get(i).getNumber()!=0){
                                    if(!mlist.get(i).getMorey().equals("")){
                                        float v = convertToFloat(mlist.get(i).getMorey(), 0);
                                        int number = mlist.get(i).getNumber();
                                        float s= v*number;
                                        total= total+s;
                                    }

                                }
                            }
                            EventBusResereBean eventBusBean=new EventBusResereBean();
                            eventBusBean.setType(4);
                            eventBusBean.setId(incrementIncreaseSaveBean.getData().getCid()+"");
                            String s1=   total+"";
                            if(s1.equals("0.0")){
                                eventBusBean.setMoney("");
                            }else{
                                eventBusBean.setMoney(total+"");
                            }
                            EventBus.getDefault().post(eventBusBean); //普通事件发布
                            finish();
                        }
                    }
                });

    }

    private void showDateService() {
        OkHttpUtils.post()
                .url(Api.POST_SCHEDULED_SERVICE)
                .addHeader("flag", SPUtils.get(IncrementServiceActivity.this, "token", "").toString())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "增值服务onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "增值服务onResponse   " + response);
                        BeanBean beanBean= JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("4")){
                            SPUtils.put(mContext,"token","");
                            Intent intent = new Intent(mContext, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        IncrementServiceBean incrementServiceBean = JsonUtils.parseByGson(response, IncrementServiceBean.class);
                        if (beanBean.getCode().equals("0")) {
                            for (int i = 0; i < incrementServiceBean.getData().getList().size(); i++) {
                                IncrementServiceBean.DataBean.ListBean listBean = incrementServiceBean.getData().getList().get(i);
                                ServiceBean serviceBean = new ServiceBean();
                                if(getmlist.size()!=0){
                                    for (int j = 0; j <getmlist.size() ; j++) {
                                        if(getmlist.get(j).getId().equals(listBean.getId()+"")){
                                            serviceBean.setMorey(getmlist.get(j).getMorey());
                                            serviceBean.setNumber(getmlist.get(j).getNumber());
                                            break;
                                        }else{
                                            serviceBean.setMorey("");
                                            serviceBean.setNumber(0);
                                        }
                                    }
                                }else{
                                    serviceBean.setMorey("");
                                    serviceBean.setNumber(0);
                                }
                                serviceBean.setId(listBean.getId() + "");
                                serviceBean.setName(listBean.getName() + "");
                                mlist.add(serviceBean);
                            }
                            rvIncrement.setLayoutManager(new LinearLayoutManager(IncrementServiceActivity.this));
                            RBaseAdapter<ServiceBean> serviceBeanRBaseAdapter = new RBaseAdapter<ServiceBean>(IncrementServiceActivity.this,
                                    R.layout.item_increment_activity, mlist) {
                                @Override
                                protected void fillItem(RViewHolder holder, ServiceBean item, int position) {
                                    TextView text_name = holder.itemView.findViewById(R.id.text_name);
                                    EditText edit_morey = holder.itemView.findViewById(R.id.edit_morey);
                                    ImageView jian = holder.itemView.findViewById(R.id.jian);
                                    TextView text_number = holder.itemView.findViewById(R.id.text_number);
                                    ImageView jia = holder.itemView.findViewById(R.id.jia);
                                    if (item.getNumber() == 0) {
                                        if(anIntid.equals("")&&anIntid==null) {
                                            mlist.get(position).setMorey("");
                                        }
                                        text_number.setText("");
                                        jian.setVisibility(View.GONE);
                                        edit_morey.setVisibility(View.GONE);
                                    } else if(item.getNumber()>0) {
                                        text_number.setText("" + item.getNumber());
                                        jian.setVisibility(View.VISIBLE);
                                        edit_morey.setVisibility(View.VISIBLE);
                                    }
                                    text_name.setText("" + item.getName());
                                    edit_morey.setText("" + item.getMorey());
//                                    edit_morey.addTextChangedListener(new TextWatcher() {
//                                        @Override
//                                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//                                        }
//
//                                        @Override
//                                        public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//                                        }
//
//                                        @Override
//                                        public void afterTextChanged(Editable s) {
//                                            if (!s.toString().equals("")) {
//                                                Log.e("TAG",position+"  123");
////                                                for (int i = 0; i <mlist.size() ; i++) {
////                                                    Log.e("TAG",mlist.get(i).getId()+"   "+item.getId());
////                                                    if(item.getId().equals(""+mlist.get(i).getId())){
//                                                        mlist.get(position).setMorey(edit_morey.getText().toString());
////                                                    }
////                                                }
//                                            }
//                                        }
//                                    });
                                    jian.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            int number = item.getNumber() - 1;
                                            if (number >= 0) {
                                                mlist.get(position).setNumber(number);
                                                mlist.get(position).setMorey(edit_morey.getText().toString());
                                            }
                                            else{
                                                if(anIntid.equals("")&&anIntid==null) {
                                                    mlist.get(position).setMorey("");
                                                }
                                            }
                                            notifyItemChanged(position);
                                        }
                                    });
                                    jia.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            int number = item.getNumber() + 1;
                                            mlist.get(position).setNumber(number);
                                            mlist.get(position).setMorey(edit_morey.getText().toString());
                                            notifyItemChanged(position);
                                        }
                                    });
                                }

                                @Override
                                protected int getViewType(ServiceBean item, int position) {
                                    return 0;
                                }
                            };
                            rvIncrement.setAdapter(serviceBeanRBaseAdapter);

                        }

                    }
                });
    }

    public class ServiceBean {
        private String id;
        private String name;
        private String money;
        private int num;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getMorey() {
            return money;
        }

        public void setMorey(String morey) {
            this.money = morey;
        }

        public int getNumber() {
            return num;
        }

        public void setNumber(int number) {
            this.num = number;
        }
    }

    public static float convertToFloat(String number, float defaultValue) {
        if (TextUtils.isEmpty(number)) {
            return defaultValue;
        }
        try {
            return Float.parseFloat(number);
        } catch (Exception e) {
            return defaultValue;
        }

    }

}